package com.object;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.core.map.MapUtil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class DashScopeClient {
    public static void main(String[] args) {
        String apiKey = "sk-cff16118fea646a7b205394ff42056d6";

        String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

        // 构建请求体 JSON 数据
        String body = "{\n" +
                "    \"model\": \"qwen-plus\",\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"system\",\n" +
                "            \"content\": \"You are a helpful assistant.\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": \"你是谁？\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"stream\": true\n" +
                "}";

        try {
            HttpResponse response = HttpRequest.post(url)
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(body)
                    .timeout(10000) // 设置超时时间
                    .execute();

             int index=0;
            try (InputStream input = response.bodyStream()) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(index+":"+line); // 逐行打印流式数据
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}